package com.wing.warehouse.controller.admin.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.utils.JsonResult;
import com.wing.product.dao.WarehouseProductInventoryDao;
import com.wing.product.model.entity.WarehouseOutboundRecordDetail;
import com.wing.product.model.entity.WarehouseProductInventory;
import com.wing.product.service.WarehouseProductInventoryService;
import com.wing.warehouse.dao.WarehouseFactoryShelfSpaceDao;
import com.wing.warehouse.model.entity.WarehouseFactoryShelfSpaceEntity;
import com.wing.warehouse.model.entity.WarehouseFactoryShelfSpaceVO;
import com.wing.warehouse.model.request.WarehouseFactoryShelfSpaceForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 仓库货架货位-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class WarehouseFactoryShelfSpaceServiceImpl extends ServiceImpl<WarehouseFactoryShelfSpaceDao, WarehouseFactoryShelfSpaceEntity> implements WarehouseFactoryShelfSpaceService{

    @Autowired
    WarehouseProductInventoryDao warehouseProductInventoryDao;
    @Override
    public int add(WarehouseFactoryShelfSpaceForm warehouseShelfSpaceForm) {

        //校验

        WarehouseFactoryShelfSpaceEntity warehouseShelfSpace =new WarehouseFactoryShelfSpaceEntity();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(WarehouseFactoryShelfSpaceEntity.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseShelfSpaceForm, warehouseShelfSpace, copyOptions);

        return baseMapper.insert(warehouseShelfSpace);
    }

    @Override
    public List<WarehouseFactoryShelfSpaceVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public   List<WarehouseFactoryShelfSpaceVO> selectFactoryCount(List<Long> ids) {
        return baseMapper.selectFactoryCount(ids);
    }

    @Override
    public Page<WarehouseFactoryShelfSpaceVO> pageList4app(Page page, Map<String, Object> params) {
        List<WarehouseFactoryShelfSpaceVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public WarehouseFactoryShelfSpaceVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }
    @Override
    public int disableByShelfId(Long shelfId) {
        return baseMapper.disableByShelfId(shelfId);
    }

    @Override
    public int updateShelfSpaceById(WarehouseFactoryShelfSpaceEntity warehouseShelfSpace) {
        return baseMapper.updateShelfSpaceById(warehouseShelfSpace);
    }

    @Override
    public WarehouseFactoryShelfSpaceVO findByCode(String code) {
        return baseMapper.findByCode(code);
    }

    @Override
    public List<WarehouseFactoryShelfSpaceVO> getShelfSpace(String skuCode, Long warehouseId) {
        return baseMapper.getShelfSpace(skuCode, warehouseId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addFlat(WarehouseFactoryShelfSpaceForm warehouseShelfFlatSpaceForm) {

        List<WarehouseFactoryShelfSpaceEntity> saveList = new ArrayList<>();
        if(warehouseShelfFlatSpaceForm.getFirstCode() == null || ! warehouseShelfFlatSpaceForm.getFirstCode().matches(".*\\d$")){
            return JsonResult.fail( 1001,"格式必须为数字结尾");
        }
        // 获取初始化的编码
        String prefix = warehouseShelfFlatSpaceForm.getFirstCode().replaceAll("\\d+$", ""); // 提取前面的非数字部分
        String suffix = warehouseShelfFlatSpaceForm.getFirstCode().replaceAll(".*?(\\d+)$", "$1"); // 提取最后的数字部分
        Integer firstNum = Integer.parseInt(suffix);
        WarehouseFactoryShelfSpaceEntity wss = baseMapper.selectLastNumByPrefix(prefix,prefix.length(),firstNum);
        if(ObjectUtil.isNotNull(wss)){
            return JsonResult.fail(1002,"最大库位编号为："+wss.getCode()+",请设置比它更大的值");
        }
        for ( int i = firstNum ; i< firstNum+ warehouseShelfFlatSpaceForm.getSpaceNum() ; i++){
            WarehouseFactoryShelfSpaceEntity warehouseShelfSpace =new WarehouseFactoryShelfSpaceEntity();
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(WarehouseFactoryShelfSpaceEntity.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(warehouseShelfFlatSpaceForm, warehouseShelfSpace, copyOptions);
            warehouseShelfSpace.setCode(prefix+(i));
            // 货架Id 不能为空 默认 -1  表示 平仓货架
            warehouseShelfSpace.setShelfId(-1L);
            saveList.add(warehouseShelfSpace);
        }
        if(saveBatch(saveList)){
            return JsonResult.success();
        }else{
            return JsonResult.fail("保存失败");

        }
    }

    @Override
    public List<WarehouseFactoryShelfSpaceEntity> selectProductSpace(String id){

        //查询产品明细
        LambdaQueryWrapper<WarehouseProductInventory> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WarehouseProductInventory::getWarehouseProductId,id)
                .eq(WarehouseProductInventory::getIsDeleted,0);
        List<WarehouseProductInventory> warehouseProductInventoryList = warehouseProductInventoryDao.selectList(lambdaQueryWrapper);
        //收集库位id，根据库位id查询库位
        Set<Long> warehouseShelfSpaceIds = warehouseProductInventoryList.stream().map(WarehouseProductInventory::getWarehouseShelfSpaceId).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(warehouseShelfSpaceIds)){
            LambdaQueryWrapper<WarehouseFactoryShelfSpaceEntity> lambdaQueryWrapperSpace = new LambdaQueryWrapper<>();
            lambdaQueryWrapperSpace.in(WarehouseFactoryShelfSpaceEntity::getId,warehouseShelfSpaceIds)
                    .eq(WarehouseFactoryShelfSpaceEntity::getIsDeleted,0);
            List<WarehouseFactoryShelfSpaceEntity> warehouseFactoryShelfSpaceEntities = this.baseMapper.selectList(lambdaQueryWrapperSpace);
            return  warehouseFactoryShelfSpaceEntities;
        }else {
            return null;
        }
    }
}
